#include "mysocketsrv.h"

#include <QTcpServer>
#include <QTcpSocket>
#include <QDebug>

#include "data/mycachedata.h"
#include "data/receivedata.h"
#include "data/myfunc.h"
#include "data/datadef.h"

TcpClient::TcpClient(int _socketID,QTcpSocket* _pSocket)
    : socketID(_socketID)
    , m_pSocket(_pSocket)
{
	connect(m_pSocket, SIGNAL(disconnected()), this, SLOT(disObj()));
	connect(m_pSocket, SIGNAL(readyRead()),this, SLOT(dataReceived()));
    qRegisterMetaType<QAbstractSocket::SocketError>("MySocketError");
    connect(m_pSocket,SIGNAL(error(QAbstractSocket::SocketError))
            ,this,SLOT(sockeError(QAbstractSocket::SocketError)));
}

TcpClient::~TcpClient()
{
    qInfo() << QString("TcpClient::Destroyed");
}

void TcpClient::myDestroy()
{
    //2018-03-13禅师开启退出策略，解决win下退出不彻底问题
    try{
        qInfo() << QString("TcpClient::myDestroy(%1)").arg(socketID);
//        disconnect(m_pSocket, SIGNAL(disconnected()), this, SLOT(disObj()));
        disconnectMyHost();
        destroyTcpSocket();
        qInfo() << QString("TcpClient::myDestroy");
    }catch(...){
        qDebug() << QString("TcpClient::myDestroy Exception");
    }
}

bool TcpClient::disconnectMyHost()
{
    try{
        if(NULL==m_pSocket){
            return true;
        }
        if(QAbstractSocket::ConnectedState==m_pSocket->state()){
            qInfo() << QString("TcpClient disconnect(%1,%2,%3)")
                        .arg(socketID).arg(m_pSocket->peerName()).arg(m_pSocket->peerPort());
            m_pSocket->disconnectFromHost();
            bool ret = m_pSocket->waitForDisconnected();
            if(ret)
            {
                qInfo() << "MySocketTran::disconnectMyHost";
            }
            return ret;
        }else if(QAbstractSocket::UnconnectedState==m_pSocket->state()){
            return true;
        }else{
            return false;
        }
    }catch(...){
        qDebug() << "MySocketTran::disconnectMyHost Exception";
        return true;
    }
}

bool TcpClient::destroyTcpSocket()
{
    try{
        if(NULL!=m_pSocket){
            disconnect(m_pSocket, SIGNAL(readyRead()),this, SLOT(dataReceived()));
            disconnect(m_pSocket,SIGNAL(error(QAbstractSocket::SocketError))
                    ,this,SLOT(sockeError(QAbstractSocket::SocketError)));
            m_pSocket = NULL;
            qInfo() << QString("TcpClient::destroyTcpSocket");
        }
    }catch(...){
        qDebug() << QString("TcpClient::destroyTcpSocket Exception");
        return false;
    }
    return true;
}

void TcpClient::sockeError(QAbstractSocket::SocketError error)
{
    if(NULL==m_pSocket)
        return;
    switch (error) {
    case QAbstractSocket::ConnectionRefusedError:
        break;
    case QAbstractSocket::RemoteHostClosedError:
        break;
    case QAbstractSocket::HostNotFoundError:
        break;
    case QAbstractSocket::SocketAccessError:
        break;
    case QAbstractSocket::SocketResourceError:
        break;
    case QAbstractSocket::SocketTimeoutError:
        return;//
    case QAbstractSocket::DatagramTooLargeError:
        break;
    case QAbstractSocket::NetworkError:
        break;
    case QAbstractSocket::AddressInUseError:
        break;
    case QAbstractSocket::SocketAddressNotAvailableError:
        break;
    case QAbstractSocket::UnsupportedSocketOperationError:
        break;
    case QAbstractSocket::ProxyAuthenticationRequiredError:
        break;
    case QAbstractSocket::SslHandshakeFailedError:
        break;
    case QAbstractSocket::UnfinishedSocketOperationError:
        break;
    case QAbstractSocket::ProxyConnectionRefusedError:
        break;
    case QAbstractSocket::ProxyConnectionClosedError:
        break;
    case QAbstractSocket::ProxyConnectionTimeoutError:
        break;
    case QAbstractSocket::ProxyNotFoundError:
        break;
    case QAbstractSocket::ProxyProtocolError:
        break;
    case QAbstractSocket::OperationError:
        break;
    case QAbstractSocket::SslInternalError:
        break;
    case QAbstractSocket::SslInvalidUserDataError:
        break;
    case QAbstractSocket::TemporaryError:
        break;
    case QAbstractSocket::UnknownSocketError:
        break;
    default:
        break;
    }
    qWarning() << QString("socket(%1,%2) error:"+m_pSocket->errorString())
                .arg(socketID).arg(m_pSocket->peerName());
}

void TcpClient::devSend(int devID,int devType,QString name)
{
    try{
        if(NULL==m_pSocket)
            return;
        if(!m_pSocket->isOpen())
            return;
        qInfo() << QString("TcpClient::devSend(%1,%2,%3)")
                    .arg(devID).arg(devType).arg(name);
        int idx = 0;
        unsigned char buf[512] = {0};
        buf[idx++]=0XF3;
        //信息长度
        buf[idx++] = 0xf0;		//1-Len_L
        buf[idx++] = 0xf0;		//2-Len_H
        //devid
        buf[idx++] = (unsigned char)(devID & 0xff);
        buf[idx++] = (unsigned char)((devID >> 8) & 0xff);
        buf[idx++] = (unsigned char)((devID >> 16) & 0xff);
        buf[idx++] = (unsigned char)((devID >> 24) & 0xff);
        //devtype
        buf[idx++] = (unsigned char)(devType & 0xff);
        buf[idx++] = (unsigned char)((devType >> 8) & 0xff);
        buf[idx++] = (unsigned char)((devType >> 16) & 0xff);
        buf[idx++] = (unsigned char)((devType >> 24) & 0xff);

    //    char Buf[512]={0};
    //    sprintf(Buf,"%s",name.toStdString().c_str());
    ////    strncpy((char *)buf+idx,(char*)Buf,bufLen);
    //    int bufLen = (int)strlen(Buf);
    //    memcpy(buf+idx,Buf,bufLen);
    //    idx += bufLen;
        #ifdef ANDROID
        memcpy(buf+idx,name.toLocal8Bit().data(),name.toLocal8Bit().length());
        idx += static_cast<int>(name.toLocal8Bit().length());
        #else
        memcpy(buf+idx,name.toStdString().data(),name.toStdString().length());
        idx += static_cast<int>(name.toStdString().length());
        #endif

        buf[1] = static_cast<unsigned char>(idx & 0xff);
        buf[2] = static_cast<unsigned char>((idx >> 8) & 0xff);
    //    printf("len(%d)\n",idx);
        unsigned char m_end = 0xFF;
        memcpy(buf+idx,&m_end,1);
        idx++;

        unsigned char _buf[256]={0};
        int nLen = code(buf, idx, _buf);
    //    QByteArray _wd((const char*)_buf,nLen);
    //    for(int j=0; j<nLen;j++){
    //        printf("%02X",_buf[j]);
    //    }
    //    printf("\n");
        m_pSocket->write((const char*)_buf, nLen);
//        m_pSocket->flush();
        bool ret = m_pSocket->waitForBytesWritten();
        if(!ret){
            qWarning() << QString("TcpClient::devSend(%1,%2,%3) fail")
                        .arg(devID).arg(devType).arg(name);
        }
    }catch(...){
        qDebug() << QString("TcpClient::devSend(%1,%2,%3) Exception")
                    .arg(devID).arg(devType).arg(name);
    }
}

void TcpClient::pointSend(int devID,int pID, int pType, QString name, float defval)
{
    try{
        if(NULL==m_pSocket)
            return;
        if(!m_pSocket->isOpen())
            return;
        qInfo() << QString("TcpClient::pointSend(%1,%2,%3,%4,%5)")
                    .arg(devID).arg(pID).arg(pType).arg(name).arg(defval,0,'f',2);
        int idx = 0;
        unsigned char buf[512] = {0};
        buf[idx++]=0XF4;
        //信息长度
        buf[idx++] = 0xf0;		//1-Len_L
        buf[idx++] = 0xf0;		//2-Len_H
        //devid
        buf[idx++] = (unsigned char)(devID & 0xff);
        buf[idx++] = (unsigned char)((devID >> 8) & 0xff);
        buf[idx++] = (unsigned char)((devID >> 16) & 0xff);
        buf[idx++] = (unsigned char)((devID >> 24) & 0xff);
        //pid
        buf[idx++] = (unsigned char)(pID & 0xff);
        buf[idx++] = (unsigned char)((pID >> 8) & 0xff);
        buf[idx++] = (unsigned char)((pID >> 16) & 0xff);
        buf[idx++] = (unsigned char)((pID >> 24) & 0xff);
        //ptype
        buf[idx++] = (unsigned char)(pType & 0xff);
        buf[idx++] = (unsigned char)((pType >> 8) & 0xff);
        buf[idx++] = (unsigned char)((pType >> 16) & 0xff);
        buf[idx++] = (unsigned char)((pType >> 24) & 0xff);
        //defval
        unsigned char*vavch = (unsigned char*)&defval;
        buf[idx++] = vavch[3];
        buf[idx++] = vavch[2];
        buf[idx++] = vavch[1];
        buf[idx++] = vavch[0];

    //    char Buf[512]={0};
    //    sprintf(Buf,"%s",name.toStdString().c_str());
    //    int bufLen = (int)strlen(Buf);
    ////    strncpy((char *)buf+idx,(char*)Buf,bufLen);
    //    memcpy(buf+idx,Buf,bufLen);
    //    idx += bufLen;
        #ifdef ANDROID
        memcpy(buf+idx,name.toLocal8Bit().data(),name.toLocal8Bit().length());
        idx += static_cast<int>(name.toLocal8Bit().length());
        #else
        memcpy(buf+idx,name.toStdString().data(),name.toStdString().length());
        idx += static_cast<int>(name.toStdString().length());
        #endif
        buf[1] = static_cast<unsigned char>(idx & 0xff);
        buf[2] = static_cast<unsigned char>((idx >> 8) & 0xff);
        unsigned char m_end = 0xFF;
        memcpy(buf+idx,&m_end,1);
        idx++;

        unsigned char _buf[256]={0};
        int nLen = code(buf, idx, _buf);
    //    QByteArray _wd((const char*)_buf,nLen);
    //    for(int j=0; j<nLen;j++){
    //        printf("%02X",_buf[j]);
    //    }
    //    printf("\n");
        m_pSocket->write((const char*)_buf, nLen);
        //        m_pSocket->flush();
        bool ret = m_pSocket->waitForBytesWritten();
        if(!ret)
        {
            qWarning() << QString("TcpClient::pointSend(%1,%2,%3,%4,%5) fail")
                        .arg(devID).arg(pID).arg(pType).arg(name).arg(defval,0,'f',2);
        }
    }catch(...){
        qDebug() << QString("TcpClient::pointSend(%1,%2,%3,%4,%5) Exception")
                    .arg(devID).arg(pID).arg(pType).arg(name).arg(defval,0,'f',2);
    }
}

void TcpClient::sendItem(int devID,int pID,int sc, int msc,float val)
{
    try{
        if(NULL==m_pSocket)
            return;
        if(!m_pSocket->isOpen())
            return;
    //    qInfo() << QString("TcpClient::sendItem(%1,%2,%3,%4,%5)")
    //                .arg(devID).arg(pID).arg(sc).arg(msc).arg(val,0,'f',2);
        int idx = 0;
        unsigned char buf[512] = {0};
        buf[idx++]=0XF5;
        //信息长度
        buf[idx++] = 0xf0;		//1-Len_L
        buf[idx++] = 0xf0;		//2-Len_H
        //devid
        buf[idx++] = (unsigned char)(devID & 0xff);
        buf[idx++] = (unsigned char)((devID >> 8) & 0xff);
        buf[idx++] = (unsigned char)((devID >> 16) & 0xff);
        buf[idx++] = (unsigned char)((devID >> 24) & 0xff);
        //pid
        buf[idx++] = (unsigned char)(pID & 0xff);
        buf[idx++] = (unsigned char)((pID >> 8) & 0xff);
        buf[idx++] = (unsigned char)((pID >> 16) & 0xff);
        buf[idx++] = (unsigned char)((pID >> 24) & 0xff);
        //sc
        buf[idx++] = (unsigned char)(sc & 0xff);
        buf[idx++] = (unsigned char)((sc >> 8) & 0xff);
        buf[idx++] = (unsigned char)((sc >> 16) & 0xff);
        buf[idx++] = (unsigned char)((sc >> 24) & 0xff);
        //msc
        buf[idx++] = (unsigned char)(msc & 0xff);
        buf[idx++] = (unsigned char)((msc >> 8) & 0xff);
        buf[idx++] = (unsigned char)((msc >> 16) & 0xff);
        buf[idx++] = (unsigned char)((msc >> 24) & 0xff);
        //val
        unsigned char*vavch = (unsigned char*)&val;
        buf[idx++] = vavch[3];
        buf[idx++] = vavch[2];
        buf[idx++] = vavch[1];
        buf[idx++] = vavch[0];

        buf[1] = static_cast<unsigned char>(idx & 0xff);
        buf[2] = static_cast<unsigned char>((idx >> 8) & 0xff);
        unsigned char m_end = 0xFF;
        memcpy(buf+idx,&m_end,1);
        idx++;

        unsigned char _buf[256]={0};
        int nLen = code(buf, idx, _buf);
    //    QByteArray _wd((const char*)_buf,nLen);
    //    for(int j=0; j<nLen;j++){
    //        printf("%02X",_buf[j]);
    //    }
    //    printf("\n");
        m_pSocket->write((const char*)_buf, nLen);
//        m_pSocket->flush();
        bool ret =m_pSocket->waitForBytesWritten();
        if(!ret)
        {
            qWarning() << QString("TcpClient::sendItem(%1,%2,%3,%4,%5) fail")
                        .arg(devID).arg(pID).arg(sc).arg(msc).arg(val,0,'f',2);
        }
    }catch(...){
        qDebug() << QString("TcpClient::sendItem(%1,%2,%3,%4,%5) Exception")
                    .arg(devID).arg(pID).arg(sc).arg(msc).arg(val,0,'f',2);
    }
}

void TcpClient::dataReceived()
{
    try{
        if(NULL==m_pSocket)
            return;
        if(!m_pSocket->isOpen())
            return;
        // qInfo() <<"read data now!\n";

        while(m_pSocket->bytesAvailable())
        {
            QByteArray vTemp;
            vTemp = m_pSocket->readAll();

            unsigned char * pBuf = new unsigned char[vTemp.length()];
            int nLen = uncode((const unsigned char *)vTemp.data(), vTemp.length(), pBuf);
            unsigned char type = pBuf[0];
            int idx = 1;
            switch (type)
            {
            case 0XF6:
            {
                int len = pBuf[idx++];
                len += (pBuf[idx++] << 8);
                //
                int devID = 0;
                devID += pBuf[idx++];
                devID += (pBuf[idx++] << 8);
                devID += (pBuf[idx++] << 16);
                devID += (pBuf[idx++] << 24);
                //
                int pID = 0;
                pID += pBuf[idx++];
                pID += (pBuf[idx++] << 8);
                pID += (pBuf[idx++] << 16);
                pID += (pBuf[idx++] << 24);
                //
                float value = float(0.0);
                unsigned char* fval = (unsigned char*)&value;
                fval[3] = pBuf[idx++];
                fval[2] = pBuf[idx++];
                fval[1] = pBuf[idx++];
                fval[0] = pBuf[idx++];
                //
                unsigned char endflag = pBuf[nLen-1];
                if(0XFF!=endflag){
                    qWarning() << QString("dataReceived error end,len(%1)").arg(len+1);
                }else{
                    qInfo() << QString("controlCmd(%1,%2,%3)").arg(devID).arg(pID).arg(value,0,'f',2);
                    emit controlCmd(devID,pID,value);
                }
            }
                break;
            default:
                break;
            }
            delete [] pBuf;
        }
    }catch(...){
        qDebug() << QString("TcpClient::dataReceived() Exception");
    }
}

void TcpClient::disObj()
{
    emit socketDestroyed(socketID);
}

int TcpClient::code(const unsigned char *buff, const int len, unsigned char *outbuf)
{
    try{
        char ch = 0;
        int nLen = 0;
        unsigned char * buf = (unsigned char *)buff;
        for (int i = 0; i < len; i++, nLen++)
        {
            ch = buf[i];
            if ((buf[i] | 0x0f) == 0xff && i > 0 && i < (len - 1))
            {
                *outbuf++ = 0xf0 & buf[i];
                *outbuf++ = 0x0f & buf[i];
                nLen += 1;
            }
            else {
                *outbuf++ = ch;
            }
        }
        return nLen;
    }catch(...){
        return 0;
    }
}

int TcpClient::uncode(const unsigned char *buff, int len, unsigned char *outbuf)
{
    try{
        char ch = 0;
        int nLen = 0;
        unsigned char * buf = (unsigned char *)buff;
        for (int i = 0; i < len; i++, nLen++)
        {
            ch = buf[i];
            if (buf[i] == 0xf0)
            {
    #ifdef _DEBUG
                if (i > len - 2)
                    printf("Error!\r\n");
                if (buf[i + 1] > 0x0f)
                    printf("Error!\r\n");
    #endif
                ch = 0xf0 | buf[++i];
            }
            *outbuf++ = ch;
        }
        return nLen;
    }catch(...){
        return 0;
    }
};

///////////////////////////////////////////////////////////////

//
ClientThread::ClientThread(MySocketSrv *m_MySocketSrv,QObject *parent)
    : QThread(parent)
    , running(true)
    , ptr_MySocketSrv(m_MySocketSrv)
{

}

ClientThread::~ClientThread()
{
    running=false;
    try{
        this->terminate();
        this->wait();
        ptr_MySocketSrv = NULL;
        qInfo() << "ClientThread::destroy\n";
    }catch(...){
        qDebug() << "ClientThread::destroy fail\n";
    }
}

void ClientThread::stopRun()
{
    running=false;
}

void ClientThread::run()
{
    while (running) {
        ptr_MySocketSrv->writeData();
        this->msleep(10);
    }
    exec();
};
//
///////////////////////////////////////////////////////////////

MySocketSrv::MySocketSrv()
    : mycache(MyCacheData::getInstance())
    , m_ReceiveData(ReceiveData::getInstance())
    , socketIndex(1)
    , m_pServer(NULL)
    , m_ClientThread(NULL)
{
    init();
}

MySocketSrv::~MySocketSrv()
{
    qInfo() << "MySocketSrv::destroy ClientThread\n";
    if(NULL!=m_ClientThread){
        m_ClientThread->stopRun();
//        m_ClientThread->deleteLater();
        delete m_ClientThread;
        m_ClientThread = NULL;
    }
    qInfo() << "MySocketSrv::destroy Server listen\n";
    if(NULL!=m_pServer){
        stopListen();
        delete m_pServer;
        m_pServer = NULL;
    }
    qInfo() << "MySocketSrv::destroy clients\n";
    disObjTcpAll();
    qInfo() << "MySocketSrv::destroy\n";
}

void MySocketSrv::init()
{
    listenPort = mycache->getPortLocal();
    m_pServer = new QTcpServer(this);
    connect(m_pServer, SIGNAL(newConnection()), this, SLOT(newConnectionSlot()));
    isListen();
    m_ClientThread = new ClientThread(this);
    m_ClientThread->start();
    heartTime = mycache->getSec();
}

bool MySocketSrv::isListen()
{
    if (!m_pServer->isListening())
    {
        if (!m_pServer->listen(QHostAddress::Any, listenPort))
        {
            return false;
        }
    }
    qInfo() << "listen now!\n";
    return true;
}

void MySocketSrv::stopListen()
{
    if (m_pServer->isListening())
    {
        m_pServer->close();
    }
}

void MySocketSrv::newConnectionSlot()
{
    try{
        qInfo() << "new connect now!\n";
        QTcpSocket *m_pSocket = m_pServer->nextPendingConnection();
        TcpClient *m_TcpClient = new TcpClient(socketIndex,m_pSocket);
        connect(m_TcpClient,SIGNAL(controlCmd(long,long,float))
                ,this,SLOT(control(long,long,float)));
        connect(m_TcpClient,SIGNAL(socketDestroyed(int)),this,SLOT(disObjTcp(int)));

        connect(this,SIGNAL(sendItem(int ,int ,int , int ,float ))
                ,m_TcpClient,SLOT(sendItem(int ,int ,int , int ,float )));
        initInfoSend(m_TcpClient);
//        m_TcpClient->moveToThread(m_ClientThread);
        //
        mutex_client.lock();
        m_pSockets.insert(socketIndex,m_TcpClient);
        mutex_client.unlock();
        socketIndex+=1;
        if(socketIndex>10000){
            socketIndex = 1;
        }
    }catch(...){
        qDebug() << "MySocketSrv::newConnectionSlot Exception";
    }
}

void MySocketSrv::initInfoSend(TcpClient* tcpC)
{
    try{
        qInfo()<< "MySocketSrv::initInfoSend";
        QList<DevClient> devs = mycache->getDevInfo();
        qInfo()<< QString("MySocketSrv::initInfoSend devs.size(%1)")
                   .arg(devs.size());
        for(QList<DevClient>::iterator itdev = devs.begin();
            itdev!=devs.end(); itdev++){
            tcpC->devSend(itdev->devID,itdev->devType,itdev->name);
            QList<PointClient> ps = mycache->getPointInfo(itdev->devID);
            qInfo()<< QString("MySocketSrv::initInfoSend ps.size(%1,%2)")
                       .arg(itdev->devID).arg(ps.size());
            for(QList<PointClient>::iterator itp = ps.begin();itp!=ps.end();itp++)
            {
                tcpC->pointSend(itdev->devID,itp->pID,itp->pType,itp->name,itp->defval);
            }
        }
    }catch(...){
        qDebug() << "MySocketSrv::initInfoSend Exception";
    }
}

void MySocketSrv::control(long devID, long pID, float val)
{
    PFromDev _pfrom;
    if (mycache->getFromInfo(devID, (int)pID, _pfrom))
    {
        float _val = val;
        mycache->getCValue(devID, static_cast<unsigned int>(pID), _val);
        if(OnYX==_pfrom.pType)
        {
            _val = _val > 0 ? float(1.0) : float(0.0);
        }
        RDS rds(OnSet,_pfrom.pID, _pfrom.pType, _val);
        m_ReceiveData->addRDS(rds);
        qInfo() << QString("setPValue from client to ip[%1],time(%2),devID(%3),pID(%4),val(%5),down_control")
                    .arg(_pfrom.ipStr).arg(PFunc::getCurrentTime())
                    .arg(devID).arg(pID).arg(val,0,'f',2);
    }
    else {
        float _val = val;
        bool sendflag = false;
        bool recordflag = false;
        int  clientType = 1;
        mycache->setValue(devID,static_cast<unsigned int>(pID),_val
            , sendflag, recordflag, clientType);
        qInfo() << QString("setPValue from client,time(%1),devID(%2),pID(%3),val(%4),down_control")
                    .arg(PFunc::getCurrentTime())
                    .arg(devID).arg(pID).arg(val,0,'f',2);
//        qint64 _usec = mycache->getUsec();
//        //client
//        if (sendflag)
//        {
//            WDC _wdlc(static_cast<unsigned long long>(devID), pID
//                , static_cast<unsigned int>(_usec/1000)
//                , static_cast<unsigned int>(_usec%1000), _val, clientType);
//            m_ReceiveData->addWDLC(_wdlc);
////            if (mycache->getMcsClientFunc()) {
////                m_ReceiveData->addWDLS(_wdlc);
////            }
//        }
    }
}

void MySocketSrv::writeData()
{
//    qInfo()<< "MySocketSrv writeData";
    WDC wdlc;
    if (m_ReceiveData->getFirstWDLC(wdlc))
    {
//        qInfo()<< "writeData wdc info";
        heartTime = mycache->getSec();
        emit sendItem(wdlc.devID,wdlc.pID,wdlc.evtTimeS,wdlc.evtTimeMS,wdlc.val);
        if (!m_ReceiveData->removeFirstWDLC())
        {
//            printf("removeFirstWDLC Error\n");
            qWarning() << ("removeFirstWDLC Error\n");
        }
    }else{
        if ((heartTime+5) < mycache->getSec())
        {
            qInfo()<< "writeData heartbreak info";
            heartTime = mycache->getSec();
            emit sendItem(-1,-1,0,0,float(0.0));
        }
    }
}

void MySocketSrv::disObjTcpAll()
{
    mutex_client.lock();
    QMap<int,TcpClient*>::iterator it=m_pSockets.begin();
    while(it!=m_pSockets.end()){
        it.value()->myDestroy();
        it.value()->deleteLater();
        it = m_pSockets.erase(it);
    }
    mutex_client.unlock();
}

void MySocketSrv::disObjTcp(int sid)
{
    mutex_client.lock();
    QMap<int,TcpClient*>::iterator it=m_pSockets.find(sid);
    if(it!=m_pSockets.end()){
        it.value()->myDestroy();
        it.value()->deleteLater();
        m_pSockets.erase(it);
    }
    mutex_client.unlock();
}
